<?php
namespace app\admin\controller;
use app\common\controller\AdminBase;
/*门店管理管理*/
class Shop extends AdminBase{
	protected $beforeActionList = [
        'before_index'=>['only'=>'index'],
    ];
	function _initialize() {
		$filter=array("shop_info");
    	if(!in_array(request()->action(),$filter)){
    		parent::_initialize();
    	}
    }
	/*门店列表*/
	function index(){
		$this->assign("shops",db("Shop")->cache("ShopsNameList",3600)->where("parent_id!=0")->order("parent_id desc,shop_name desc")->column("shop_name"));
		echo $this->fetch();
	}	
	//删除门店
	function delete(){
		$id=input("id");
		$model=db("Shop")->where("id=$id")->find();
		if(empty($model['parent_id'])){//父类
			$count=db("Shop")->where("parent_id=".$model['id'])->count(1);
			if(!empty($count)){
				$this->ajax_error("存在子类，请先删除子类");			
			}
		}
		cache("AnkeConfig_".input("id"),null);
		db("Shop")->where("id =$id")->delete();
		$this->ajax_success("成功");
	}
	function edit(){
		$model=db("Shop")->find(input('id'));
		$this->assign("parents",db("shop")->where("parent_id=0")->select());
		$this->assign("model",$model);
		$this->assign("apis",db("ApiTemplate")->field("id,name,api_version")->select());
		echo $this->fetch();	
	}
	function edit_post(){
		if(request()->isPost()){//提交
		    $old_shop_name=input("old_shop_name");
		    $flag=db("Shop")->where("shop_name='".input('shop_name')."' and shop_name!='$old_shop_name'")->count(1);
			if($flag>0){
			 	$this->ajax_error("门店名称已经存在");
			}
			db("Shop")->update(array("id"=>input("id"),"shop_name"=>input("shop_name"),"parent_id"=>input("parent_id"),"api_version"=>input("api_version"),'extra_config'=>htmlspecialchars_decode(input("extra_config"))));
			cache("ExtraConfig_".input("id"),null);
			$this->ajax_success("成功");
		}
	}
	
	/*设置菜单*/
	function set_menu(){
		$id=input("id");
		if(empty($id)){
			$shop_id=input("shop_id");
			if(empty($shop_id)){
				$this->ajax_error("失败！");
			}
			$menu_id=db("ShopMenu")->where("shop_id=$shop_id")->value("id");
			if(empty($menu_id)){
				$data=db('ShopMenu')->fetchSql(FALSE)->insert($_POST);
			}else{
				$_POST['id']=$menu_id;
				$data=db('ShopMenu')->where("id=$menu_id and shop_id=$shop_id")->update(array(
					"pool_1"=>input("pool_1"),
					"pool_2"=>input("pool_2"),
					"pool_3"=>input("pool_3"),
				));
			}
			$this->ajax_success("成功！",$data);	
		}else{
			    $shop=db("Shop")->where("id=$id")->find();
				if(empty($shop)||empty($shop['parent_id'])){
					echo "<H1>品牌无需设置</H1>";die;
				}
				$menu=sp_get_all_menu();
				if(isset($menu['1000'])){
					unset($menu['1000']);	
				}
				$this->assign("menus",$menu);
				$this->assign("model",db("ShopMenu")->where("shop_id=$id")->find());
				$this->assign("shop_id",$id);
				echo $this->fetch();
		}
	}
	/*设置店铺pc机器上的配置*/
	function set_pc_config(){
		$shop_id=input("id");
		if(empty($shop_id)){
			echo "参数错误！";die;
		}else{
			$shop=db("Shop")->where("id=$shop_id")->find();
				if(empty($shop)||empty($shop['parent_id'])){
					echo "<H1>品牌无需设置</H1>";die;
				}
			$model=db("PcConfig")->where("shop_id=$shop_id")->find();
			if(empty($model)){
				$model=array("shop_id"=>$shop_id,"server_url"=>"","shop_code"=>"","browser"=>1,"pic_version"=>0,"locker_version"=>1,"card_keys"=>"","is_locker"=>1,"gym_type"=>0,"off_line_in"=>0,"off_line"=>0,"model_count"=>1);
				$this->assign("id",0);
			}else{
				$this->assign("id",$model['id']);
			}
			$this->assign("model",$model);
		}
		$this->assign("shop",db("Shop")->find($shop_id));
		echo $this->fetch();
	}

	/*设置店铺pc机器上的配置*/
	function detail(){
		$shop_id=sp_get_current_shop_id();
		if(empty($shop_id)){
			echo "参数错误！";die;
		}else{
			$shop=db("Shop")->where("id=$shop_id")->find();
			$model=db("PcConfig")->where("shop_id=$shop_id")->find();
			if(empty($model)){
				$model=array("shop_id"=>$shop_id,"server_url"=>"","shop_code"=>"","browser"=>1,"pic_version"=>0,"locker_version"=>1,"card_keys"=>"","is_locker"=>1,"gym_type"=>0,"off_line_in"=>0,"off_line"=>0,"reader_version"=>input("reader_version",1),"model_store_type"=>input("model_store_type",0),"model_count"=>1);
				$this->assign("id",0);
			}else{
				$this->assign("id",$model['id']);
			}
			$this->assign("model",$model);
			$this->assign("shop",$shop);
			$auth_code=config("admin_auth_code")['auth_code'];
			if(!isset($auth_code[$shop_id])){
				$this->assign("auth_code","暂无授权码");
			}else{
				$this->assign("auth_code",$auth_code[$shop_id]);
			}
			
		}
		echo $this->fetch();
	}

	function set_pc_config_post(){
		if(empty(input("id"))){
		   	db("PcConfig")->insert(
				array(
						"server_url"=>input("server_url"),
						"shop_code"=>input("shop_code"),
						"shop_id"=>input("shop_id"),							
						"browser"=>input("browser"),
						"pic_version"=>input("pic_version"),
						"locker_version"=>input("locker_version"),
						"card_keys"=>input("card_keys"),
						"is_locker"=>input("is_locker"),
						"gym_type"=>input("gym_type"),
						"off_line"=>input("off_line"),
						"off_line_in"=>input("off_line_in"),
						"model_count"=>input("model_count"),	 	 	
				)
		);
		}else{
		$sql=db("PcConfig")->where("id=".input("id"))->update(
				array(
						"server_url"=>input("server_url"),
						"shop_code"=>input("shop_code"),
						"browser"=>input("browser"),
						"pic_version"=>input("pic_version"),
						"locker_version"=>input("locker_version"),
						"card_keys"=>input("card_keys"),
						"is_locker"=>input("is_locker"),
						"gym_type"=>input("gym_type"),
						"off_line"=>input("off_line"),
						"off_line_in"=>input("off_line_in"),	 
						"model_count"=>input("model_count"),
				)
			);
		}
		return $this->ajax_success();
	}
	
	/*卡列表数据*/
	function ajax_index(){
		$this->ajax($this->_ajax_index());
	}
	
	function add(){
		$this->assign("parents",db("shop")->where("parent_id=0")->select());
		$this->assign("apis",db("ApiTemplate")->field("id,name,api_version")->select());
		echo $this->fetch();
	}
	
	function add_post(){
		if(request()->isPost()){
			$flag=db("Shop")->where("shop_name='".input('shop_name')."'")->count(1);
			if($flag>0){
			 	$this->ajax_error("门店名称已经存在");
			}
			if(empty(input("parent_id"))){
				db("Shop")->insert(array("shop_name"=>input("shop_name"),"parent_id"=>0,"api_version"=>null));
				$this->ajax_success("成功");
			}
			$this->varify_uniq();
			
			$shop_id=db("Shop")->insertGetId(array("shop_name"=>input("shop_name"),"parent_id"=>input("parent_id"),"api_version"=>input("api_version"),'extra_config'=>htmlspecialchars_decode(input('extra_config'))));
			if(!empty(input("parent_id"))){
				$this->shop_init($shop_id,input("account"),input("password"));
				db("Shop")->where("id=$shop_id")->update(array("shop_code"=>date("mdY").$shop_id));
			}
		    $this->ajax_success("成功");
		}
	}
   /**验证管理员账号唯一**/
	function varify_uniq(){
		$account=input("account");
		$count=db("admin")->where("account='$account'")->count(1);
		if($count>0){
			$this->ajax_error("账号已经存在");
		}
	}
	///////////////////////////////////////////////////////////////////////////////////
	/**
	 * 权限菜单
	 **/
	function before_index(){
		$auth_group=sp_get_auth_menu_3("10001000");
		$this->assign("menus",$auth_group);
	}
	/**
	 * 验证门店信息
	 * http://zwzl.ocmcom.com/Admin/Shop/shop_info
	 * */
	function shop_info(){
			$shop_id=input("shop_id");
			$shop_name=input("shop_name");
			if(empty($shop_id)||empty($shop_name)){
				$this->ajax_error("参数错误");
			}else{
				$model=db("shop")->where("id='$shop_id' and shop_name='$shop_name'")->fetchsql(FALSE)->find();
				if(empty($model)){
					$this->ajax_error("配置错误");
				}else{
					$this->ajax_success("成功");
				}
			}
	}
	/*获取卡数据*/
	private function _ajax_index(){
		$query=array(
		 'shop_name'=>array("field" =>"shop_name","operator" =>"="),
		 );
		 $shop_id=sp_get_current_shop_id();
		 $draw=input("draw",0)+1;//请求时间		 
		$where_and=join(" and ",sp_get_param_sql(request()->isPost(),$query));
		if(!empty($shop_id)){
		  $where_and=" and id=$shop_id";
		}
		$total=db("Shop")->where($where_and)->count(1);
		$list=db("Shop")->where($where_and)->order($this->get_order())->limit($this->get_limit())->fetchsql(FALSE)->select();
		$parents=db("Shop")->where("parent_id=0")->column("shop_name","id");
		$shop_menu=db("ShopMenu")->column("shop_id");
		$pc_sets=db("PcConfig")->column("shop_id");
		if(empty($shop_menu)){
			$shop_menu=[];
		}
		foreach ($list as $key => $value) {
			if(!empty($parents)&&in_array($value['parent_id'],array_keys($parents))){
				$list[$key]['parent_name']=$parents[$value['parent_id']];					
			}
			if(in_array($value['id'],$shop_menu)){
				$list[$key]["has_menu"]=1;
			}else{
				$list[$key]["has_menu"]=0;
			}
			if(in_array($value["id"],$pc_sets )){
			    $list[$key]["pc_set"]=1;	
			}else{
				$list[$key]["pc_set"]=0;
			}
		}
		return array('pageData'=>$list,'total'=>$total,"draw"=>$draw);
	}
	/**
	 * 新增店铺后 需要初始化的数据
	 * */
	   public  function shop_init($shop_id,$account,$password){
		$data=config("sliding_door");
	 	if(empty($shop_id)){
	 		return ;
	 	}
		//添加店铺管理员账号
	 	db("Admin")->insert(array("name"=>"shop_owner",'account'=>$account,"password"=>md5($password),"shop_id"=>$shop_id,'is_shop_admin'=>1));
		//添加滑门
		$data=config("sliding_door");
		foreach ($data as $key => $value) {
			$data[$key]['shop_id']=$shop_id;
		}
		db("SlidingDoor")->insertAll($data);
		//新增系统设置
		$data=config("system_set");
		foreach ($data as $key => $value) {
			$data[$key]['shop_id']=$shop_id;
		}
		db("SystemSet")->insertAll($data);
	 }
	/*
	 * 获取api 模板
	 * */   
	 public function  get_api_template(){
	 	$api_version=input("api_version");
		$template=db("ApiTemplate")->where("api_version='$api_version'")->value("template");
		if(empty($template)){
			$this->ajax_error("无模板");
		}else{
			$this->ajax_success('成功',$template);
		}
	 }
	 
	/**
	 * 第三方接口测试
	 * */ 	 	
	public function debug(){
		$shop_id=sp_get_current_shop_id();
		$this->assign("shop",db("Shop")->find($shop_id));
	 	echo $this->fetch();
	}
	
	/**
	 * 获取合同
	 * */
	public function getcontract(){
		$api_version=input("api_version");
		$shop_id=sp_get_current_shop_id();
		$config=$this->_get_shop_config($shop_id,$api_version);
		$card_no=input("card_no");
		if($api_version=='anke'){//安科接口
			$result=http_get("http://host.gymparty.net:81/SCHWebService.asmx/GetContractInfo",['BrandCode'=>$config['BrandCode'],"ClubID"=>$config['ClubID'],"CardNo"=>$card_no,"Mobile"=>"","Key"=>$config['Key']]);
			$this->ajax($result);
		}elseif($api_version=='qingniao'){//勤鸟接口
			$result=http_get("http://zwzlcloud.ocmcom.com/Api/QnSync/GetContractInfo",['card_no'=>$card_no,'shop_id'=>$shop_id]);
			$this->ajax($result);
		}elseif($api_version==3){// 捷径接口
			
		}elseif($api_version=='dongxia'){//东夏接口
			$url=$config['url'];
	    	$dxshopid=$config['dxshopid'];
			$loginid=$config['loginid'];
			$password=$config['password'];
			$result=http_get($url."/GetMemberInfo",['cardindex'=>$card_no,'shopid'=>$dxshopid,"loginid"=>$loginid,"password"=>$password,"mode"=>"only_in","brushnum"=>2,"repeat"=>"yes","billtype"=>"new","shopname"=>"","loginname"=>"","projectname"=>""]);
			$this->ajax($result);
		}elseif($api_version=='locals'){//本地判断
			 $this->ajax_success("",json_encode(action("api/LocalsApi/GetContractInfo",['card_no'=>$card_no,'shop_id'=>$shop_id]),JSON_UNESCAPED_UNICODE));
		}elseif($api_version=='ziyoudao'){//自由岛
			$mobile=input("mobile");
		    if(empty($mobile)||strlen($mobile)!=11){
		     	return $this->ajax_error("手机号码格式错误！");
		    }
			$url=$config['url'];
	    	$appid=$config['appid'];
			$deviceID=$config['deviceID'];
			$category=$config['category'];
			$uid=$this->GetUid($card_no, $mobile, $shop_id);
			$sign_str="appid".$appid."category".$category."deviceID".$deviceID."numType"."1"."numValue".$mobile."uid".$uid;
			$sign=array("sign:".md5($sign_str));
			$result=post_json($url."/bindUserVeinFinger",['numValue'=>$mobile,"numType"=>"1",'appid'=>$appid,"deviceID"=>$deviceID,"uid"=>$uid,"category"=>$category],$sign);
			$this->ajax_success("",json_encode($result,JSON_UNESCAPED_UNICODE));
		}elseif($api_version=='ziyouren'){//智游人
			$member_id=db("Interface")->where("card_no='$card_no' and shop_id=$shop_id")->value("member_id");
			$result=http_get("http://clubacylm.smartfuns.com/v1/member/syncMemberInfo",['CardNo'=>$card_no,'BranchID'=>$config['BranchID'],"DoorID"=>$shop_id,"MemberID"=>$member_id]);
			if($result['flag']){
				$json= $this->decrypt($result['data'],$config);
				if($json['Result']==1){
						return $this->ajax_success("",$json);
					}else{
						$this->ajax_error($this->zyr_error($json['Result']));
				}			
			}else{
				 $this->ajax_error($result['msg']);
			}
		}elseif($api_version=='ocm'){//ocm
			return action("api/GymApi/GetContractInfo",['card_no'=>$card_no,'shop_id'=>$shop_id]);
		}elseif($api_version=='jiangougou'){//健狗狗
			return action("api/JGGApi/GetContractInfo",['card_no'=>$card_no,'shop_id'=>$shop_id]);
		}elseif($api_version=='vjian'){//微键
			$appId=$config['appId'];
			$deviceId=$config['deviceId'];
			$clubId=$config['clubId'];
			$url=$config['url'];
			$result= http_post($url."Wx/Ocmcom/Api/getVipuserInfo",['appId'=>$appId,"deviceId"=>$deviceId,'ClubID'=>$clubId,"CardNo"=>$card_no]);
			$this->ajax($result);
		}
		return $this->ajax_error("","0003","非法访问！");
	 
	}
private function zyr_error($code){
		$error=array('0'=>"失败(zyr)",'1'=>"成功","2"=>"参数不全(zyr)","3"=>"无效的BranchID(zyr)","4"=>"无效的CardNo(zyr)","5"=>"卡没绑定会员(zyr)");
		if(!isset($error[$code])){
			return "未知错误(zyr)！";
		}else{
			return $error[$code];
		}
	}
	 /**
	 * 解密
	 */
	private function decrypt($data,$config){
		$result=openssl_decrypt(base64_decode($data), "aes-256-cbc", $config['Key'], true, str_repeat(chr(0), 16));
		if(empty($result)){
			$this->ajax_error('','',"请配置智游人代码(解密错误)");
		}else{
			return json_decode($result,TRUE);
		}
	} 
	 /*入场*/
	function check_in(){
		$api_version=input("api_version");
		$shop_id=sp_get_current_shop_id();
		$config=$this->_get_shop_config($shop_id,$api_version);
		$card_no=input("card_no");
		$interface=db("Interface")->where("card_no='$card_no' and shop_id=$shop_id and owner_type=1")->find();
		if(empty($interface)){
			$this->ajax_error("会员在系统中不存在");
		}
		if($api_version=='anke'){//安科接口
			$result=http_get("http://host.gymparty.net:81/SCHWebService.asmx/CheckIn",['BrandCode'=>$config['BrandCode'],"ClubID"=>$config['ClubID'],"ContractID"=>$interface['contract_id'],"MemberID"=>$interface['member_id'],"Key"=>$config['Key']]);
			$this->ajax($result);
		}elseif($api_version=='qingniao'){//勤鸟接口
			$result=http_get("http://zwzlcloud.ocmcom.com/Api/QnSync/CheckIn",['card_no'=>$card_no,'shop_id'=>$shop_id]);
			$this->ajax($result);
		
		}elseif($api_version==3){// 捷径接口
			
		}elseif($api_version=='dongxia'){//东夏接口
			$url=$config['url'];
	    	$dxshopid=$config['dxshopid'];
			$loginid=$config['loginid'];
			$password=$config['password'];
			$result=http_get($url."/CheckCardindex",['cardindex'=>$card_no,'shopid'=>$dxshopid,"loginid"=>$loginid,"password"=>$password,"shopname"=>"","loginname"=>""]);
			$this->ajax($result);
		}elseif($api_version=='locals'){//本地判断
			$this->ajax_success("",json_encode(action("api/LocalsApi/CheckIn",['card_no'=>$card_no,'shop_id'=>$shop_id]),JSON_UNESCAPED_UNICODE));
		}elseif($api_version=='ziyoudao'){//自由岛
		     //自由岛
			$url=$config['url'];
	    	$appid=$config['appid'];
			$deviceID=$config['deviceID'];
			$category=$config['category'];
			$mobile=input("mobile");
			$uid=$this->GetUid($card_no, $mobile, $shop_id);
			$sign_str="appid".$appid."category".$category."deviceID".$deviceID."numType"."1"."numValue".$mobile."uid".$uid;
			$sign=array("sign:".md5($sign_str));
			$member_id=db("Interface")->where("card_no='$card_no' and shop_id=$shop_id")->value("member_id");
			$result=post_json($url."/turnoverNotice",['appid'=>$appid,"deviceID"=>$deviceID,"uid"=>$member_id,"type"=>0,"category"=>$category]);
			$this->ajax_success("",json_encode($result,JSON_UNESCAPED_UNICODE));
		}elseif($api_version=='ziyouren'){
			//智游人
			$member_id=db("Interface")->where("card_no='$card_no' and shop_id=$shop_id")->value("member_id");
			$result=http_get("http://clubacylm.smartfuns.com/v1/access/in",['CardNo'=>$card_no,'BranchID'=>$config['BranchID'],"DoorID"=>$shop_id,"MemberID"=>$member_id]);
			if($result['flag']){
				$json= $this->decrypt($result['data'],$config);
				if($json['Result']==1){
						$this->ajax_success("",$json);
					}else{
						$this->ajax_error($this->zyr_error($json['Result']));
				}			
			}else{
				 $this->ajax_error($result['msg']);
			}
		
		}elseif($api_version=='ocm'){//ocm
			return action("api/GymApi/GetContractInfo",['card_no'=>$card_no,'shop_id'=>$shop_id]);
		}elseif($api_version=='jiangougou'){//健狗狗
			return action("api/JGGApi/GetContractInfo",['card_no'=>$card_no,'shop_id'=>$shop_id]);
		}elseif($api_version=='vjian'){//微键
			$appId=$config['appId'];
			$deviceId=$config['deviceId'];
			$clubId=$config['clubId'];
			$url=$config['url'];
			$result= http_post($url."Wx/Ocmcom/Api/enter",['appId'=>$appId,"ClubID"=>$clubId,"deviceId"=>$deviceId,"CardNo"=>$card_no]);
			$this->ajax($result);
		}
		return $this->ajax_error("","0003","非法访问！");
	 
	
	} 
	function _get_shop_config($shop_id,$api_version){
		if(empty($shop_id)){
			$this->ajax_error("店铺id空");
		}else{
			$config=db("Shop")->where("id=".$shop_id." and api_version='$api_version'")->value("extra_config");
			if(empty($config)){
				$this->ajax_error('配置代码为空');
			}
			return json_decode($config,TRUE);
		}
	}
	
	/**
	 * 获取uid
	 */
	function GetUid($card_no,$mobile,$shop_id){
		$uid=db("Interface")->where("card_no='$card_no' and mobile='$mobile' and shop_id=$shop_id " )->value("member_id");
		if(empty($uid)){
				return time();
		}else{
			return $uid;
		}
	}
	/**
	 * 获取合同
	 * */
	public function getptlist(){
		$api_version=input("api_version");
		$config=$this->_get_shop_config(sp_get_current_shop_id(),$api_version);
		if($api_version=='anke'){//安科接口
			$result= http_post("http://host.gymparty.net:81/CSmart/SCHWebService.asmx/GetPTEmployeeList",['BrandCode'=>$config['BrandCode'],"ClubID"=>$config['ClubID'],"Key"=>$config['Key']]);
			$this->ajax($result);
		}elseif($api_version=='qingniao'){//勤鸟接口
			$this->ajax_error("暂未开放");
		}elseif($api_version==3){// 捷径接口
			$this->ajax_error("暂未开放");
		}elseif($api_version=='dongxia'){//东夏接口
			$this->ajax_error("暂未开放");
		}elseif($api_version=='locals'){//本地判断
			$this->ajax_error("暂未开放");
		}elseif($api_version=='ziyoudao'){
			$this->ajax_error("暂未开放");
		}elseif($api_version=='ziyouren'){
			$this->ajax_error("暂未开放");
		}elseif($api_version=='ocm'){
			$this->ajax_error("暂未开放");
		}elseif($api_version=='jiangougou'){
			$this->ajax_error("暂未开放");
		}elseif($api_version=='vjian'){
			$appId=$config['appId'];
			$deviceId=$config['deviceId'];
			$clubId=$config['clubId'];
			$url=$config['url'];
			$result= http_post($url."wx/ocmcom/api/GetPTEmployeeList",['appId'=>$appId,"ClubID"=>$clubId,"deviceId"=>$deviceId]);
			$this->ajax($result);
		}
		return $this->ajax_error("","0003","非法访问！");
	}
}
